#pragma once

#include <iostream>
#include <unordered_map>
#include <string>
#include <cassert>
#include <vector>
#include <fstream>
#include <cstdlib>

#include "../comm/util.hpp"
#include "../comm/log.hpp"

// 根据question.list文件，加载所有的题目信息到内存中（实际上开销很小）
// model : 主要用来与数据进行交互，对外提供访问数据的接口

namespace ns_model
{
    using namespace std;
    using namespace ns_log;
    using namespace ns_util;

    struct Question
    {
        std::string number; // 题号
        std::string title;  // 标题
        std::string star;   // 难度：简单、中等、困难
        int cpu_limit;      // cpu资源限制(s)
        int mem_limit;      // mem资源限制(KB)
        std::string desc;   // 题目描述
        std::string header; // 题目预设给用户的在线编辑器代码
        std::string tail;   // 测试用例，与header拼接
    };

    const std::string questions_list = "./questions/questions.list";
    const std::string qeustions_path = "./questions/";
    class Model
    {
    private:
        // 题号 : 题目细节
        unordered_map<string, Question> questions;

    public:
        Model()
        {
            assert(LoadQuestionList(questions_list));
        }
        ~Model() {}

        bool LoadQuestionList(const std::string &questions_list)
        {
            // 加载配置文件: questions/questions.list + 题目编号文件
            ifstream in(questions_list);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载题库失败，请检查相应文件是否存在" << "\n";
                return false;
            }

            std::string line;
            while (getline(in, line))
            {
                vector<string> tokens;
                StringUtil::SplitString(line, &tokens, " ");
                if (tokens.size() != 5)
                {
                    LOG(WARNING) << "加载部分题目失败，请检查文件格式" << "\n";
                    continue;
                }
                Question q;
                q.number = tokens[0];
                q.title = tokens[1];
                q.star = tokens[2];
                q.cpu_limit = atoi(tokens[3].c_str());
                q.mem_limit = atoi(tokens[4].c_str());

                std::string path = qeustions_path;
                path += q.number;
                path += "/";

                // FileUtil::ReadFile(path + "desc.txt", &(q.desc), true);
                if (!FileUtil::ReadFile(path + "desc.txt", &(q.desc), true))
                {
                    LOG(WARNING) << "无法读取文件: " << path + "desc.txt" << "\n";
                    continue;
                }

                FileUtil::ReadFile(path + "header.cpp", &(q.header), true);
                FileUtil::ReadFile(path + "tail.cpp", &(q.tail), true);

                questions.insert({q.number, q});
            }
            LOG(INFO) << "加载题库成功" << "\n";
            in.close();

            return true;
        }

        bool GetAllQuestions(vector<Question> *out)
        {
            if (questions.size() == 0)
            {
                LOG(ERROR) << "获取题库失败" << "\n";
                return false;
            }
            for (const auto &q : questions)
            {
                out->push_back(q.second);
            }
            return true;
        }

        bool GetOneQuestion(const std::string &number, Question *q)
        {
            const auto &iter = questions.find(number);
            if (iter == questions.end())
            {
                LOG(ERROR) << "加载题目：" << number << "失败" << "\n";
                return false;
            }
            (*q) = iter->second;
            return true;
        }
    };
}